<?php
namespace App\DBs\Stock;

use Illuminate\Support\Facades\DB;

class BoardDB extends BaseDB
{
    /**
     * 创板
     */

    protected $table = 'stock_board';
    protected $tSource = 'stock_board_source'; //创板素材

    /**
     * 创板字段
     * uid 用户UID
     * uname 用户名
     * vid 库视频ID
     * plus 创作ID
     * isRender 1未申请，2申请中，3已渲染，
     */

    /**
     * 创板素材字段
     * uid 用户UID
     * vid 库视频ID
     * plus 创作ID
     * bid 创板ID
     * serial 编号顺序
     * link 素材地址或文字
     */

    public function __construct()
    {
    }

    /**
     * 后台列表
     */
    public function getAdminIndex($page, $size, $vid, $uid)
    {
        $pageStart = $page * $size;
        $query = DB::table($this->table)
            ->orderBy('id','desc');
        if ($vid) { $query = $query->where('vid',$vid); }
        if ($uid) { $query = $query->where('uid',$uid); }
        $queryTotal = $query->count();
        $models = $query->skip($pageStart)
            ->take($size)
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        $dataArr = array();
        foreach ($models as $model) {
            $dataArr[] = [
                'boardId' => $model['id'],
                'uid' => $model['uid'],
                'uname' => $model['uname'],
                'vid' => $model['vid'],
                'boardName' => $model['caseName'],
                'vlink' => $model['vlink'],
                'del' => $model['del'],
            ];
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr, 'total'=>$queryTotal);
    }

    /**
     * 后台库视频
     */
    public function getAdminCases()
    {
        $vids = array();
        $dataArr = array();
        $models = DB::table($this->table)
            ->orderBy('id','asc')
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据', 'data'=>$dataArr);
        }
        $models = $this->jsonToArr($models);
        foreach ($models as $model) {
            if (!in_array($model['vid'],$vids)) {
                $resStocks = DB::table($this->tStock)
                    ->where('id',$model['vid'])
                    ->orderBy('id','desc')
                    ->skip(0)->take(1)
                    ->get();
                $stockOne = count($resStocks) ? $this->jsonToArr($resStocks[0]) : '';
                $stockTitle = $stockOne ? $stockOne['fileTitle'] : '';
                $dataArr[] = [
                    'videoId' => $model['vid'],
                    'videoTitle' => $stockTitle,
                ];
                $vids[] = $model['vid'];
            }
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr);
    }

    /**
     * 后台用户
     */
    public function getAdminUsers()
    {
        $uids = array();
        $dataArr = array();
        $models = DB::table($this->table)
            ->orderBy('id','asc')
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据', 'data'=>$dataArr);
        }
        $models = $this->jsonToArr($models);
        foreach ($models as $model) {
            if (!in_array($model['uid'],$uids)) {
                $resUser = $this->getUnameByUid($model['uid']);
                $dataArr[] = [
                    'uid' => $model['uid'],
                    'uname' => $resUser,
                ];
                $uids[] = $model['uid'];
            }
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr);
    }

    /**
     * APP列表
     */
    public function getAppSourceIndex($uid, $bid)
    {
        $query = DB::table($this->tSource)
            ->where('del',0);
        $query = $query->where('uid',$uid)
            ->where('bid',$bid);
        $queryTotal = $query->count();
        $models = $query->orderBy('serial','asc')->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        $dataArr = array();
        foreach ($models as $model) {
            $dataArr[] = [
//                'uid' => $model['uid'],
//                'bid' => $model['bid'],
                'serial' => $model['serial'],
                'type' => $model['type'],
                'link' => $model['link'],
            ];
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr, 'total'=>$queryTotal);
    }

    /**
     * 通过用户，获取一条
     */
    public function getAppOneByUid($uid,$bid)
    {
        $models = DB::table($this->table)
            ->where('del',0)
            ->where('id',$bid)
            ->where('uid',$uid)
            ->orderBy('id','desc')
            ->skip(0)->take(1)
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $dataArr = $this->jsonToArr($models[0]);
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr);
    }

    /**
     * 通过创单ID，获取一条未渲染的
     */
    public function getAppOneByPlus($uid,$plusId)
    {
        $models = DB::table($this->table)->where('del',0)
            ->where('uid',$uid)
            ->where('plus',$plusId)
            ->where('isRender',1)
            ->orderBy('id','desc')
            ->skip(0)->take(1)
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $dataArr = $this->jsonToArr($models[0]);
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr);
    }

    /**
     * 加入创作增加
     * @param $uid 用户ID
     * @param $vid 首页视频ID
     */
    public function setAdd($items)
    {
        if (!$items) {
            return array('code'=>'-1', 'msg'=>'参数错误');
        }
        //开启事务
        DB::beginTransaction();
        try {
            $boardId = 0;
            $sourceIds = array();
            //更新创板
            $boardArr = array(
                'uid' => $items['uid'],
                'vid' => $items['vid'],
                'plus' => $items['plus'],
                'uname' => $items['uname'],
                'created_at' => time(),
            );
            $boardId = DB::table($this->table)->insertGetId($boardArr);
            //更新素材
            for ($i=1;$i<=$items['num'];$i++) {
                $sourceArr = array(
                    'uid' => $items['uid'],
                    'vid' => $items['vid'],
                    'plus' => $items['plus'],
                    'bid' => $boardId,
                    'serial' => $i,
                    'created_at' => time(),
                );
                $sourceIds[] = DB::table($this->tSource)
                    ->insertGetId($sourceArr);
            }
            $dataArr = array(
                'boardId' => $boardId,
                'sourceIds' => $sourceIds,
            );
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 更新素材内容
     */
    public function setSource($bsId, $type, $link)
    {
        if (!$bsId || !$type || !$link) {
            return array('code'=>'-1', 'msg'=>'参数错误');
        }
        //开启事务
        DB::beginTransaction();
        try {
            //更新素材
            DB::table($this->tSource)->where('id',$bsId)
                ->update(['type'=>$type, 'link'=>$link, 'updated_at'=>time()]);
            $dataArr = array();
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }
}